package com.momalib.ning2_nocode.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CommonUtils {

    public static String stringToUnicode(String str) {
        StringBuffer sb = new StringBuffer();
        char[] c = str.toCharArray();
        for (int i = 0; i < c.length; i++) {
            sb.append("\\u" + Integer.toHexString(c[i]));
        }
        return sb.toString();
    }

    public static String calcISBN13Check(String isbn13) {
        int sum = 0;
        for (int i = 0; i < 12; i++) {
            int num = isbn13.charAt(i) - 48;
            int weight = i%2 == 0 ? 1 : 3;
            sum += num * weight;
        }
        int result = 10 - sum % 10;
        return "" + result;
    }

    public static String convertISBN10TO13(String isbn10) {
        if (!checkIsInt(isbn10.substring(0, 9))) {
            return isbn10;
        }
        String subISBN = "978" + isbn10.substring(0, 9);
        return subISBN + calcISBN13Check(subISBN);
    }

    public static String convertISBN13TO10(String isbn13) {
        if (!checkIsInt(isbn13)) {
            return isbn13;
        }
        String subISBN = isbn13.substring(3, 12);
        return subISBN + calcISBN10Check(subISBN);
    }

    public static String calcISBN10Check(String isbn10) {
        int sum = 0;
        for (int i = 0; i < 9; i++) {
            int num = isbn10.charAt(i) - 48;
            sum += num*(10-i);
        }
        int result = 11 - sum % 11;
        if (result == 10) {
            return "X";
        } else if (result == 11) {
            return "0";
        } else {
            return String.valueOf(result);
        }
    }

    public static int getRandomByRange(int min, int max) {
        return min + (int)(Math.random() * (max-min+1));
    }

    public static void sleepRandom(int min, int max) {
        try {
            Thread.sleep(getRandomByRange(min, max));
        } catch (Exception e){}
    }

    public static boolean checkIsInt(String numStr) {
        Pattern pattern = Pattern.compile("[0-9]+");
        Matcher isNum = pattern.matcher(numStr);
        return isNum.matches();
    }

    public static String bytesToHex(byte[] hash) {
        StringBuilder hexString = new StringBuilder(2 * hash.length);
        for (int i = 0; i < hash.length; i++) {
            String hex = Integer.toHexString(0xff & hash[i]);
            if(hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }

    public static String getMD5(String originStr) {
        try {
            byte[] bytesOfMessage = originStr.getBytes(StandardCharsets.UTF_8);
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] theMD5digest = md.digest(bytesOfMessage);
            return bytesToHex(theMD5digest);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    public static String getRandomString(int length){
        String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random=new Random();
        StringBuffer sb=new StringBuffer();
        for(int i=0;i<length;i++){
            int number=random.nextInt(62);
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }

    public static String getFileNameHash(byte[] data) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-512");
            byte[] messageDigest = md.digest(data);

            Base64.Encoder encoder = Base64.getEncoder();
            String result = encoder.encodeToString(messageDigest);
            result = result.replace(".", "_");
            result = result.replace("/", "-");
            result = result.replace("\\", "_-");
            return result;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static String obj2JsonStr(Object obj) {
        ObjectMapper mapper = new ObjectMapper();
        String resultStr = null;
        try {
            resultStr = mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
//            throw new RuntimeException(e);
            e.printStackTrace();
        }
        return resultStr;
    }

    public static <T> T json2Obj(String jsonStr, Class<T> objClass) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.readValue(jsonStr, objClass);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static <T> T json2Obj(String jsonStr, TypeReference<T> valueTypeRef) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.readValue(jsonStr, valueTypeRef);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static long tryGetLong(String longStr) {
        long longVal = 0L;
        try {
            longVal = Long.parseLong(longStr);
        } catch (Exception e) {
//            e.printStackTrace();
        }
        return longVal;
    }

    public static long mapGetLong(Map<String, Object> map, String key) {
        Object longObj = map.get(key);
        long longVal = 0L;

        if (longObj instanceof String) {
            longVal = Long.parseLong((String) longObj);
        } else if (longObj instanceof Long) {
            longVal = (Long) longObj;
        }

        return longVal;
    }

    public static boolean isToday(Date date) {
        SimpleDateFormat fmt=new SimpleDateFormat("yyyy-MM-dd");
        fmt.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
        return fmt.format(date).equals(fmt.format(new Date()));
    }


    public static void main(String[] args) {
    }
}
